import fs from 'fs-extra';
import path from 'path';
import * as ts from 'typescript';
import * as vueDocgen from 'vue-docgen-api';
import { ComponentParser } from './parser';
import { TypeAnalyzer } from './typeAnalyzer';
import { CodeAnalyzer } from './codeAnalyzer';
import { ComponentProp, VueComponent, ComponentEvent, ComponentSlot, ComponentMethod } from '../core/types';

/**
 * 增强型Vue组件解析器
 * 扩展基本解析器，提供更强大的类型推导和无注释情况下的组件分析能力
 */
export class EnhancedComponentParser extends ComponentParser {
  private typeAnalyzer: TypeAnalyzer;
  private codeAnalyzer: CodeAnalyzer;

  /**
   * 构造函数
   * @param scanPaths 要扫描的组件路径
   * @param vueVersion Vue版本 (2, 3, 或 auto)
   */
  constructor(scanPaths: string[], vueVersion: string = 'auto') {
    super(scanPaths, vueVersion);
    this.typeAnalyzer = new TypeAnalyzer();
    this.codeAnalyzer = new CodeAnalyzer();
    console.log('初始化增强型组件解析器');
  }

  /**
   * 增强解析单个组件
   * @param filePath 组件文件路径
   */
  protected async parseComponent(filePath: string): Promise<VueComponent | null> {
    // 首先使用基础解析器获取组件基本信息
    const baseComponent = await super.parseComponent(filePath);
    if (!baseComponent) {
      return null;
    }

    try {
      // 读取文件内容
      const content = await fs.readFile(filePath, 'utf-8');
      
      // 使用代码分析器提取更多信息
      const codeAnalysis = this.codeAnalyzer.analyze(content, baseComponent.vueVersion === '3');
      
      // 合并组件信息
      const enhancedComponent: VueComponent = {
        ...baseComponent,
        props: await this.enhanceProps(baseComponent.props, codeAnalysis.props, content, filePath, baseComponent.vueVersion),
        events: this.enhanceEvents(baseComponent.events, codeAnalysis.events, content, baseComponent.vueVersion),
        slots: this.enhanceSlots(baseComponent.slots, codeAnalysis.slots, content, baseComponent.vueVersion),
        methods: this.enhanceMethods(baseComponent.methods, codeAnalysis.methods, content, baseComponent.vueVersion),
      };
      
      return enhancedComponent;
    } catch (error) {
      console.error(`增强解析组件 ${filePath} 失败:`, error);
      // 出错时返回基础解析结果
      return baseComponent;
    }
  }

  /**
   * 增强组件属性解析
   */
  private async enhanceProps(
    baseProps: ComponentProp[], 
    analyzedProps: ComponentProp[],
    content: string, 
    filePath: string, 
    vueVersion: '2' | '3'
  ): Promise<ComponentProp[]> {
    // 合并从代码分析中获取的属性
    const mergedProps = [...baseProps];
    
    // 过滤代码分析中找到的新属性，确保只添加真实的组件属性
    const filteredAnalyzedProps = this.filterNonPropItems(analyzedProps, content, vueVersion);
    
    // 添加从代码分析中找到的新属性
    filteredAnalyzedProps.forEach(analyzedProp => {
      if (!mergedProps.some(p => p.name === analyzedProp.name)) {
        mergedProps.push(analyzedProp);
      }
    });
    
    // 尝试从代码中提取注释描述
    this.extractCommentDescriptions(mergedProps, content);
    
    // 如果属性描述仍为空，尝试从变量名称自动生成描述
    mergedProps.forEach(prop => {
      if (!prop.description) {
        prop.description = this.generateDescriptionFromName(prop.name);
      }
    });

    // 尝试从TypeScript类型定义提取更多信息
    await this.extractPropTypesFromTypeScript(mergedProps, filePath, vueVersion);
    
    // 尝试提取默认值（对于 Vue 3 特别处理）
    if (vueVersion === '3') {
      this.extractVue3DefaultValues(mergedProps, content);
    } else {
      this.extractVue2DefaultValues(mergedProps, content);
    }
    
    // 推导可选值（主要是枚举类型）
    this.inferPossibleValues(mergedProps, content);
    
    // 清理默认值的显示格式
    mergedProps.forEach(prop => {
      if (prop.defaultValue) {
        prop.defaultValue = this.cleanDefaultValueDisplay(prop.defaultValue);
      }
    });
    
    return mergedProps;
  }

  /**
   * 过滤非组件属性项
   * 确保只有真正的props被识别，而不是普通变量或方法
   */
  private filterNonPropItems(props: ComponentProp[], content: string, vueVersion: '2' | '3'): ComponentProp[] {
    // 首先尝试明确查找属性定义
    let definedProps: ComponentProp[] = [];
    
    // 如果是Vue 2，检查props定义区域
    if (vueVersion === '2') {
      // 提取props定义
      const propsMatch = content.match(/props:\s*\{([^}]+)\}/s);
      if (propsMatch) {
        const propsSection = propsMatch[1];
        // 提取明确定义的属性名
        const propNamePattern = /['"]?(\w+)['"]?\s*:/g;
        let propMatch;
        while ((propMatch = propNamePattern.exec(propsSection)) !== null) {
          const propName = propMatch[1];
          const foundProp = props.find(p => p.name === propName);
          if (foundProp) {
            definedProps.push(foundProp);
          }
        }
        
        return definedProps;
      }
      
      // 如果找不到props定义区域，尝试查找props数组形式
      const propsArrayMatch = content.match(/props:\s*\[(.*?)\]/s);
      if (propsArrayMatch) {
        const propsArray = propsArrayMatch[1];
        // 提取props数组中的属性名
        const propNamePattern = /['"](\w+)['"]/g;
        let propMatch;
        while ((propMatch = propNamePattern.exec(propsArray)) !== null) {
          const propName = propMatch[1];
          const foundProp = props.find(p => p.name === propName);
          if (foundProp) {
            definedProps.push(foundProp);
          }
        }
        
        return definedProps;
      }
    } 
    // 如果是Vue 3，检查defineProps区域
    else if (vueVersion === '3') {
      // 检查defineProps<Interface>形式
      const typePropsMatch = content.match(/defineProps<([^>]+)>/s);
      if (typePropsMatch) {
        const typePropsSection = typePropsMatch[1];
        // 从接口定义中提取属性名
        const propNamePattern = /(\w+)\??:/g;
        let propMatch;
        while ((propMatch = propNamePattern.exec(typePropsSection)) !== null) {
          const propName = propMatch[1];
          const foundProp = props.find(p => p.name === propName);
          if (foundProp) {
            definedProps.push(foundProp);
          }
        }
        
        return definedProps;
      }
      
      // 检查defineProps({})形式
      const objectPropsMatch = content.match(/defineProps\(\s*\{([^}]+)\}\s*\)/s);
      if (objectPropsMatch) {
        const objectPropsSection = objectPropsMatch[1];
        // 从对象定义中提取属性名
        const propNamePattern = /['"]?(\w+)['"]?\s*:/g;
        let propMatch;
        while ((propMatch = propNamePattern.exec(objectPropsSection)) !== null) {
          const propName = propMatch[1];
          const foundProp = props.find(p => p.name === propName);
          if (foundProp) {
            definedProps.push(foundProp);
          }
        }
        
        return definedProps;
      }
      
      // 检查withDefaults(defineProps<Interface>(), {})形式
      const withDefaultsMatch = content.match(/withDefaults\(\s*defineProps<([^>]+)>\(\),\s*\{([^}]+)\}\s*\)/s);
      if (withDefaultsMatch) {
        const [, typeSection, defaultsSection] = withDefaultsMatch;
        
        // 从接口定义中提取属性名
        const typePropPattern = /(\w+)\??:/g;
        let typePropMatch;
        while ((typePropMatch = typePropPattern.exec(typeSection)) !== null) {
          const propName = typePropMatch[1];
          const foundProp = props.find(p => p.name === propName);
          if (foundProp) {
            definedProps.push(foundProp);
          }
        }
        
        // 从默认值对象中提取属性名
        const defaultPropPattern = /['"]?(\w+)['"]?\s*:/g;
        let defaultPropMatch;
        while ((defaultPropMatch = defaultPropPattern.exec(defaultsSection)) !== null) {
          const propName = defaultPropMatch[1];
          const foundProp = props.find(p => p.name === propName);
          if (foundProp && !definedProps.some(p => p.name === propName)) {
            definedProps.push(foundProp);
          }
        }
        
        return definedProps;
      }
    }
    
    // 如果没有找到明确的props定义，则返回空数组
    // 这是一个保守的方法，避免包含非属性项
    return [];
  }

  /**
   * 清理默认值的显示格式，移除代码标记
   */
  private cleanDefaultValueDisplay(defaultValue: string): string {
    // 移除引号
    let cleaned = defaultValue.replace(/^['"](.*)['"]$/, '$1');
    
    // 移除函数调用格式（如 () => 'value'）
    cleaned = cleaned.replace(/\(\)\s*=>\s*['"](.*)['"]/, '$1');
    
    // 移除 function() 格式
    cleaned = cleaned.replace(/function\s*\(\)\s*{\s*return\s*['"](.*)['"].*}/, '$1');
    
    // 对于对象或数组类型，保留但格式化
    if (cleaned.startsWith('{') || cleaned.startsWith('[')) {
      try {
        // 尝试解析并美化对象/数组
        const parsed = JSON.parse(cleaned.replace(/'/g, '"'));
        cleaned = JSON.stringify(parsed);
      } catch (e) {
        // 如果无法解析，保留原样
      }
    }
    
    return cleaned;
  }

  /**
   * 增强组件事件解析
   */
  private enhanceEvents(
    baseEvents: ComponentEvent[], 
    analyzedEvents: ComponentEvent[],
    content: string, 
    vueVersion: '2' | '3'
  ): ComponentEvent[] {
    const mergedEvents = [...baseEvents];
    
    // 过滤事件，确保只包含真正的组件事件
    const filteredAnalyzedEvents = this.filterComponentEvents(analyzedEvents, content, vueVersion);
    
    // 添加从代码分析中找到的新事件
    filteredAnalyzedEvents.forEach(analyzedEvent => {
      if (!mergedEvents.some(e => e.name === analyzedEvent.name)) {
        mergedEvents.push(analyzedEvent);
      }
    });
    
    // 寻找未记录的事件
    const undocumentedEvents = this.findUndocumentedEvents(content, vueVersion);
    
    // 合并未记录的事件
    undocumentedEvents.forEach(event => {
      if (!mergedEvents.some(e => e.name === event.name)) {
        mergedEvents.push(event);
      }
    });
    
    // 尝试从代码中提取事件注释描述
    this.extractEventCommentDescriptions(mergedEvents, content, vueVersion);
    
    return mergedEvents;
  }

  /**
   * 过滤事件，只保留真正的组件事件
   */
  private filterComponentEvents(events: ComponentEvent[], content: string, vueVersion: '2' | '3'): ComponentEvent[] {
    if (vueVersion === '3') {
      // 查找Vue 3的defineEmits定义
      const emitsMatch = content.match(/defineEmits\s*\(\s*(?:\[[^\]]+\]|\{[^}]+\}|[^)]+)\)/s);
      if (emitsMatch) {
        const emitsSection = emitsMatch[0];
        return events.filter(event => {
          const eventPattern = new RegExp(`['"]${event.name}['"]`, 'g');
          return eventPattern.test(emitsSection);
        });
      }
    }
    
    // 查找emit调用来验证事件
    return events.filter(event => {
      const emitPattern = vueVersion === '3'
        ? new RegExp(`emit\\s*\\(\\s*['"]${event.name}['"]`, 'g')
        : new RegExp(`\\$emit\\s*\\(\\s*['"]${event.name}['"]`, 'g');
      
      return emitPattern.test(content);
    });
  }

  /**
   * 从代码中提取事件注释描述
   */
  private extractEventCommentDescriptions(events: ComponentEvent[], content: string, vueVersion: '2' | '3'): void {
    events.forEach(event => {
      // 已有描述的事件跳过
      if (event.description && !event.description.startsWith('On ')) {
        return;
      }

      const eventPattern = vueVersion === '3' 
        ? `emit\\(["']${event.name}["']` 
        : `\\$emit\\(["']${event.name}["']`;

      // 尝试匹配多行注释
      const multiLineCommentPattern = new RegExp(
        `\\/\\*\\*\\s*\\n(?:\\s*\\*\\s*(?:@\\w+\\s+.*\\n|\\n|))*\\s*\\*\\s*([^@\\n].*?)\\s*\\n(?:\\s*\\*.*\\n)*(?:\\s*\\*\\/)?[^]*?${eventPattern}`
      );
      const multiLineMatch = content.match(multiLineCommentPattern);
      if (multiLineMatch && multiLineMatch[1]) {
        event.description = multiLineMatch[1].trim();
        return;
      }

      // 尝试匹配单行注释
      const singleLineCommentPattern = new RegExp(
        `\\/\\/\\s*(.*?)\\s*\\n\\s*(?:this\\.)?${eventPattern}`
      );
      const singleLineMatch = content.match(singleLineCommentPattern);
      if (singleLineMatch && singleLineMatch[1]) {
        event.description = singleLineMatch[1].trim();
        return;
      }

      // 尝试匹配内联注释
      const inlineCommentPattern = new RegExp(
        `${eventPattern}.*?\\/\\/\\s*(.*?)(?:\\n|$)`
      );
      const inlineMatch = content.match(inlineCommentPattern);
      if (inlineMatch && inlineMatch[1]) {
        event.description = inlineMatch[1].trim();
      }
    });
  }

  /**
   * 增强组件插槽解析
   */
  private enhanceSlots(
    baseSlots: ComponentSlot[], 
    analyzedSlots: ComponentSlot[],
    content: string, 
    vueVersion: '2' | '3'
  ): ComponentSlot[] {
    const mergedSlots = [...baseSlots];
    
    // 过滤插槽，确保只包含真正的组件插槽
    const filteredAnalyzedSlots = this.filterComponentSlots(analyzedSlots, content);
    
    // 添加从代码分析中找到的新插槽
    filteredAnalyzedSlots.forEach(analyzedSlot => {
      if (!mergedSlots.some(s => s.name === analyzedSlot.name)) {
        mergedSlots.push(analyzedSlot);
      }
    });
    
    // 寻找未记录的插槽
    const undocumentedSlots = this.findUndocumentedSlots(content, vueVersion);
    
    // 合并未记录的插槽
    undocumentedSlots.forEach(slot => {
      if (!mergedSlots.some(s => s.name === slot.name)) {
        mergedSlots.push(slot);
      }
    });
    
    // 尝试从代码中提取插槽注释描述
    this.extractSlotCommentDescriptions(mergedSlots, content);
    
    return mergedSlots;
  }

  /**
   * 过滤插槽，只保留真正的组件插槽
   */
  private filterComponentSlots(slots: ComponentSlot[], content: string): ComponentSlot[] {
    // 在模板中查找插槽定义
    return slots.filter(slot => {
      const slotPattern = slot.name === 'default'
        ? /<slot\b[^>]*>/g
        : new RegExp(`<slot\\s+name=["']${slot.name}["'][^>]*>`, 'g');
      
      return slotPattern.test(content);
    });
  }

  /**
   * 从代码中提取插槽注释描述
   */
  private extractSlotCommentDescriptions(slots: ComponentSlot[], content: string): void {
    slots.forEach(slot => {
      // 已有描述的插槽跳过
      if (slot.description && (slot.name !== 'default' || slot.description !== '默认插槽')) {
        return;
      }

      const slotPattern = slot.name === 'default' 
        ? `<slot\\b` 
        : `<slot\\s+name=["']${slot.name}["']`;

      // 尝试匹配多行注释
      const multiLineCommentPattern = new RegExp(
        `\\/\\*\\*\\s*\\n(?:\\s*\\*\\s*(?:@\\w+\\s+.*\\n|\\n|))*\\s*\\*\\s*([^@\\n].*?)\\s*\\n(?:\\s*\\*.*\\n)*(?:\\s*\\*\\/)?[^]*?${slotPattern}`
      );
      const multiLineMatch = content.match(multiLineCommentPattern);
      if (multiLineMatch && multiLineMatch[1]) {
        slot.description = multiLineMatch[1].trim();
        return;
      }

      // 尝试匹配单行注释
      const singleLineCommentPattern = new RegExp(
        `\\/\\/\\s*(.*?)\\s*\\n\\s*${slotPattern}`
      );
      const singleLineMatch = content.match(singleLineCommentPattern);
      if (singleLineMatch && singleLineMatch[1]) {
        slot.description = singleLineMatch[1].trim();
        return;
      }

      // 尝试匹配模板内的注释
      const templateCommentPattern = new RegExp(
        `<!--\\s*(.*?)\\s*-->\\s*${slotPattern}`
      );
      const templateMatch = content.match(templateCommentPattern);
      if (templateMatch && templateMatch[1]) {
        slot.description = templateMatch[1].trim();
      }
    });
  }

  /**
   * 增强组件方法解析
   */
  private enhanceMethods(
    baseMethods: ComponentMethod[], 
    analyzedMethods: ComponentMethod[],
    content: string, 
    vueVersion: '2' | '3'
  ): ComponentMethod[] {
    const mergedMethods = [...baseMethods];
    
    // 过滤方法，确保只包含真正的组件方法
    const filteredAnalyzedMethods = this.filterComponentMethods(analyzedMethods, content, vueVersion);
    
    // 添加从代码分析中找到的新方法
    filteredAnalyzedMethods.forEach(analyzedMethod => {
      if (!mergedMethods.some(m => m.name === analyzedMethod.name)) {
        mergedMethods.push(analyzedMethod);
      }
    });
    
    // 尝试从代码中提取方法注释描述
    this.extractMethodCommentDescriptions(mergedMethods, content, vueVersion);
    
    return mergedMethods;
  }

  /**
   * 过滤方法，只保留真正的组件方法
   */
  private filterComponentMethods(methods: ComponentMethod[], content: string, vueVersion: '2' | '3'): ComponentMethod[] {
    if (vueVersion === '2') {
      // 查找Vue 2组件的methods定义
      const methodsMatch = content.match(/methods\s*:\s*{([^}]+)}/s);
      if (methodsMatch) {
        const methodsSection = methodsMatch[1];
        return methods.filter(method => {
          const methodPattern = new RegExp(`\\b${method.name}\\s*:\\s*(function|async)?`, 'g');
          return methodPattern.test(methodsSection);
        });
      }
    } else {
      // Vue 3组件中，生命周期钩子和组件方法会暴露
      // 排除生命周期钩子和内部方法
      const lifecycleHooks = [
        'onMounted', 'onBeforeMount', 'onBeforeUpdate', 'onUpdated',
        'onBeforeUnmount', 'onUnmounted', 'onActivated', 'onDeactivated',
        'onErrorCaptured', 'onRenderTracked', 'onRenderTriggered'
      ];
      
      return methods.filter(method => {
        // 排除生命周期钩子
        if (lifecycleHooks.includes(method.name)) {
          return false;
        }
        
        // 排除下划线开头的内部方法
        if (method.name.startsWith('_')) {
          return false;
        }
        
        // 检查方法是否在defineExpose中暴露
        const exposePattern = new RegExp(`defineExpose\\s*\\(\\s*\\{[^}]*\\b${method.name}\\b`, 'g');
        if (exposePattern.test(content)) {
          return true;
        }
        
        // 排除局部函数和组件内部使用的函数
        const localFuncPattern = new RegExp(`\\bconst\\s+${method.name}\\s*=`, 'g');
        if (localFuncPattern.test(content) && !exposePattern.test(content)) {
          return false;
        }
        
        return true;
      });
    }
    
    return methods;
  }

  /**
   * 从代码中提取方法注释描述
   */
  private extractMethodCommentDescriptions(methods: ComponentMethod[], content: string, vueVersion: '2' | '3'): void {
    methods.forEach(method => {
      // 已有描述的方法跳过
      if (method.description) {
        return;
      }

      const methodPattern = vueVersion === '3' 
        ? `(const|function)\\s+${method.name}\\s*\\(` 
        : `${method.name}\\s*\\([^)]*\\)\\s*\\{`;

      // 尝试匹配多行注释
      const multiLineCommentPattern = new RegExp(
        `\\/\\*\\*\\s*\\n(?:\\s*\\*\\s*(?:@\\w+\\s+.*\\n|\\n|))*\\s*\\*\\s*([^@\\n].*?)\\s*\\n(?:\\s*\\*.*\\n)*(?:\\s*\\*\\/)?[^]*?${methodPattern}`
      );
      const multiLineMatch = content.match(multiLineCommentPattern);
      if (multiLineMatch && multiLineMatch[1]) {
        method.description = multiLineMatch[1].trim();
        return;
      }

      // 尝试匹配单行注释
      const singleLineCommentPattern = new RegExp(
        `\\/\\/\\s*(.*?)\\s*\\n\\s*(?:async\\s+)?${methodPattern}`
      );
      const singleLineMatch = content.match(singleLineCommentPattern);
      if (singleLineMatch && singleLineMatch[1]) {
        method.description = singleLineMatch[1].trim();
        return;
      }

      // 为Vue 2的methods对象中的方法查找注释
      if (vueVersion === '2') {
        const vue2MethodCommentPattern = new RegExp(
          `${method.name}:\\s*(?:async\\s+)?function\\s*\\([^)]*\\)\\s*\\{\\s*\\/\\/\\s*(.*?)\\s*\\n`
        );
        const vue2Match = content.match(vue2MethodCommentPattern);
        if (vue2Match && vue2Match[1]) {
          method.description = vue2Match[1].trim();
          return;
        }
      }

      // 从自动生成的函数名生成描述
      method.description = this.generateDescriptionFromName(method.name);
    });
  }

  /**
   * 从变量名生成描述
   */
  private generateDescriptionFromName(name: string): string {
    // 驼峰命名转换为空格分隔的单词
    const words = name.replace(/([A-Z])/g, ' $1').toLowerCase();
    // 首字母大写
    return words.charAt(0).toUpperCase() + words.slice(1);
  }

  /**
   * 从TypeScript类型定义中提取属性类型
   */
  private async extractPropTypesFromTypeScript(
    props: ComponentProp[], 
    filePath: string, 
    vueVersion: '2' | '3'
  ): Promise<void> {
    if (props.length === 0) return;
    
    try {
      // 尝试找到相关的TypeScript类型定义文件
      const componentDir = path.dirname(filePath);
      const componentName = path.basename(filePath, '.vue');
      const possibleTypeFiles = [
        path.join(componentDir, `${componentName}.d.ts`),
        path.join(componentDir, `${componentName}.types.ts`),
        path.join(componentDir, 'types.ts'),
        path.join(componentDir, 'types.d.ts')
      ];
      
      // 查找可能存在的类型文件
      for (const typeFile of possibleTypeFiles) {
        if (await fs.pathExists(typeFile)) {
          await this.typeAnalyzer.analyzeTypeFile(typeFile, props);
          break;
        }
      }
      
      // 如果没找到类型文件，尝试分析组件文件中的类型
      if (vueVersion === '3') {
        // 对于Vue 3，尝试提取defineProps中的类型
        const scriptContent = await this.extractScriptContent(filePath);
        if (scriptContent) {
          this.typeAnalyzer.analyzeComponentScript(scriptContent, props, true);
        }
      }
    } catch (error) {
      console.error(`提取TypeScript类型失败:`, error);
    }
  }

  /**
   * 提取Vue 3默认值
   */
  private extractVue3DefaultValues(props: ComponentProp[], content: string): void {
    // 在withDefaults中查找默认值
    const withDefaultsMatch = content.match(/withDefaults\(\s*defineProps<[^>]+>\(\),\s*(\{[^}]+\})\s*\)/);
    if (withDefaultsMatch) {
      const defaultsObj = withDefaultsMatch[1];
      
      // 解析默认值对象
      const defaultRegex = /(\w+):\s*([^,]+),?/g;
      let match;
      while ((match = defaultRegex.exec(defaultsObj)) !== null) {
        const [, name, defaultValue] = match;
        const prop = props.find(p => p.name === name);
        
        if (prop) {
          prop.defaultValue = defaultValue.trim();
        }
      }
    } else {
      // 查找defineProps对象形式的默认值
      const propsMatch = content.match(/defineProps\(\s*(\{[^}]+\})\s*\)/);
      if (propsMatch) {
        const propsObj = propsMatch[1];
        
        // 使用更精确的正则表达式提取默认值
        // 支持函数形式 default: () => value 或 default: function() { return value }
        const propRegex = /(\w+):\s*\{[^}]*default:\s*(?:function\s*\(\)\s*\{[^}]*return\s*([^;]+)[^}]*\}|(?:\(\)\s*=>\s*)?([^,}]+))[,}]/g;
        
        let match;
        while ((match = propRegex.exec(propsObj)) !== null) {
          const [, name, funcValue, arrowValue] = match;
          const defaultValue = (funcValue || arrowValue || '').trim();
          const prop = props.find(p => p.name === name);
          
          if (prop && defaultValue) {
            prop.defaultValue = defaultValue;
          }
        }
      }
    }
  }

  /**
   * 提取Vue 2默认值
   */
  private extractVue2DefaultValues(props: ComponentProp[], content: string): void {
    // 查找props对象
    const propsMatch = content.match(/props:\s*\{([^}]+)\}/);
    if (propsMatch) {
      const propsObj = propsMatch[1];
      
      // 使用更精确的正则表达式提取默认值
      // 支持函数形式 default: () => value 或 default: function() { return value }
      const propRegex = /(\w+):\s*\{[^}]*default:\s*(?:function\s*\(\)\s*\{[^}]*return\s*([^;]+)[^}]*\}|(?:\(\)\s*=>\s*)?([^,}]+))[,}]/g;
      
      let match;
      while ((match = propRegex.exec(propsObj)) !== null) {
        const [, name, funcValue, arrowValue] = match;
        const defaultValue = (funcValue || arrowValue || '').trim();
        const prop = props.find(p => p.name === name);
        
        if (prop && defaultValue) {
          prop.defaultValue = defaultValue;
        }
      }
    }
  }

  /**
   * 推导可能的属性值
   */
  private inferPossibleValues(props: ComponentProp[], content: string): void {
    props.forEach(prop => {
      // 如果已有values，不再推导
      if (prop.values && prop.values.length > 0) {
        return;
      }
      
      // 对布尔类型属性添加可能的值
      if (prop.type === 'boolean') {
        prop.values = ['true', 'false'];
      }
      
      // 通过名称推断可能的值
      if (
        prop.name.includes('type') || 
        prop.name.includes('mode') || 
        prop.name.includes('size') || 
        prop.name.includes('variant') ||
        prop.name.includes('position') ||
        prop.name.includes('align') ||
        prop.name.includes('status')
      ) {
        // 在组件内容中搜索条件判断，可能暗示可选值
        this.findPossibleValuesFromConditions(prop, content);
      }
    });
  }

  /**
   * 从条件语句中查找可能的值
   */
  private findPossibleValuesFromConditions(prop: ComponentProp, content: string): void {
    const conditionalChecks = [
      new RegExp(`(if|\\?)\\s*\\(\\s*${prop.name}\\s*===\\s*['"](\\w+)['"]`, 'g'),
      new RegExp(`(if|\\?)\\s*\\(\\s*${prop.name}\\s*==\\s*['"](\\w+)['"]`, 'g'),
      new RegExp(`\\(\\s*${prop.name}\\s*\\)\\s*===\\s*['"](\\w+)['"]`, 'g'),
      new RegExp(`${prop.name}\\s*===\\s*['"](\\w+)['"]`, 'g'),
      new RegExp(`case\\s*['"](\\w+)['"]`, 'g')
    ];
    
    const values = new Set<string>();
    
    // 对每种条件模式进行匹配
    conditionalChecks.forEach(regex => {
      let match;
      while ((match = regex.exec(content)) !== null) {
        const value = match[2] || match[1];
        if (value && !['true', 'false', 'undefined', 'null'].includes(value)) {
          values.add(value); // 不加引号，直接存储值
        }
      }
    });
    
    if (values.size > 0) {
      prop.values = Array.from(values);
    }
  }

  /**
   * 查找未记录的事件
   */
  private findUndocumentedEvents(content: string, vueVersion: '2' | '3'): ComponentEvent[] {
    const events: ComponentEvent[] = [];
    
    // 查找emit调用
    const emitPattern = vueVersion === '3' 
      ? /emit\(\s*['"](\w+)['"]/g
      : /\$emit\(\s*['"](\w+)['"]/g;
    
    let match;
    while ((match = emitPattern.exec(content)) !== null) {
      const eventName = match[1];
      events.push({
        name: eventName,
        description: this.generateDescriptionFromName(`on ${eventName}`),
        arguments: []
      });
    }
    
    // 对于Vue 3的defineEmits
    if (vueVersion === '3') {
      const defineEmitsMatch = content.match(/defineEmits\(\s*\[\s*(['"][\w-:]+['"]\s*,?\s*)+\]/);
      if (defineEmitsMatch) {
        const eventPattern = /['"](\w+)['"]/g;
        let eventMatch;
        while ((eventMatch = eventPattern.exec(defineEmitsMatch[0])) !== null) {
          const eventName = eventMatch[1];
          if (!events.some(e => e.name === eventName)) {
            events.push({
              name: eventName,
              description: this.generateDescriptionFromName(`on ${eventName}`),
              arguments: []
            });
          }
        }
      }
    }
    
    return events;
  }

  /**
   * 查找未记录的插槽
   */
  private findUndocumentedSlots(content: string, vueVersion: '2' | '3'): ComponentSlot[] {
    const slots: ComponentSlot[] = [];
    
    // 查找模板中的插槽
    const defaultSlotMatches = content.match(/<slot\s+[^>]*>/g);
    if (defaultSlotMatches) {
      defaultSlotMatches.forEach(match => {
        // 提取名称
        const nameMatch = match.match(/name\s*=\s*['"](\w+)['"]/);
        const slotName = nameMatch ? nameMatch[1] : 'default';
        
        // 检查是否已存在
        if (!slots.some(s => s.name === slotName)) {
          slots.push({
            name: slotName,
            description: slotName === 'default' ? '默认插槽' : this.generateDescriptionFromName(slotName),
            bindings: []
          });
        }
      });
    }
    
    return slots;
  }

  /**
   * 提取脚本内容
   */
  private async extractScriptContent(filePath: string): Promise<string | null> {
    try {
      const content = await fs.readFile(filePath, 'utf-8');
      
      // 提取<script> 或 <script setup> 块的内容
      const scriptMatch = content.match(/<script( setup)?>([\s\S]*?)<\/script>/);
      if (scriptMatch) {
        return scriptMatch[2];
      }
      
      return null;
    } catch (error) {
      console.error(`提取脚本内容失败:`, error);
      return null;
    }
  }

  /**
   * 从代码中提取注释描述
   */
  private extractCommentDescriptions(props: ComponentProp[], content: string): void {
    // 处理每个属性
    props.forEach(prop => {
      // 已有描述的属性跳过
      if (prop.description) {
        return;
      }

      // 尝试匹配多行注释模式
      const multiLineCommentPattern = new RegExp(
        `\\/\\*\\*\\s*\\n(?:\\s*\\*\\s*(?:@\\w+\\s+.*\\n|\\n|))*\\s*\\*\\s*([^@\\n].*?)\\s*\\n(?:\\s*\\*.*\\n)*(?:\\s*\\*\\/)?[^]*?${prop.name}\\s*:`
      );
      const multiLineMatch = content.match(multiLineCommentPattern);
      if (multiLineMatch && multiLineMatch[1]) {
        prop.description = multiLineMatch[1].trim();
        return;
      }

      // 尝试匹配单行注释模式 (Vue 2 风格)
      const singleLineCommentPattern = new RegExp(
        `\\/\\/\\s*(.*?)\\s*\\n\\s*${prop.name}\\s*:`
      );
      const singleLineMatch = content.match(singleLineCommentPattern);
      if (singleLineMatch && singleLineMatch[1]) {
        prop.description = singleLineMatch[1].trim();
        return;
      }

      // 尝试匹配 Vue 3 的 defineProps 注释
      if (content.includes('defineProps')) {
        // 为 defineProps 中的属性查找注释
        const vue3CommentPattern = new RegExp(
          `\\/\\/\\s*(.*?)\\s*\\n(?:\\s*\\/\\/.*\\n)*\\s*${prop.name}[?]?:`
        );
        const vue3Match = content.match(vue3CommentPattern);
        if (vue3Match && vue3Match[1]) {
          prop.description = vue3Match[1].trim();
          return;
        }
      }
      
      // 尝试匹配属性内部的注释 (Vue 2 props 对象内部)
      const propInnerCommentPattern = new RegExp(
        `${prop.name}:\\s*\\{[^}]*\\/\\*\\*\\s*(.*?)\\s*\\*\\/`
      );
      const innerMatch = content.match(propInnerCommentPattern);
      if (innerMatch && innerMatch[1]) {
        prop.description = innerMatch[1].trim();
        return;
      }

      // 尝试匹配内联注释
      const inlineCommentPattern = new RegExp(
        `${prop.name}:.*?\\/\\/\\s*(.*?)(?:\\n|$)`
      );
      const inlineMatch = content.match(inlineCommentPattern);
      if (inlineMatch && inlineMatch[1]) {
        prop.description = inlineMatch[1].trim();
      }
    });
  }
} 